/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.reddys.rad.inventory.controller;

import com.reddys.rad.inventory.db.PurchaseOrderDetails;
import com.reddys.rad.inventory.db.Sale;
import com.reddys.rad.inventory.db.SaleDetails;
import com.reddys.rad.inventory.db.Stock;
import com.reddys.rad.inventory.db.StockDetails;
import com.reddys.rad.inventory.db.Vendor;
import com.reddys.rad.inventory.service.SalesService;
import com.reddys.rad.inventory.utils.EditingCell;
import com.reddys.rad.inventory.utils.Utilities;
import eu.schudt.javafx.controls.calendar.DatePicker;
import inventory.Inventory;
import java.net.URL;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.Locale;
import java.util.ResourceBundle;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableColumn.CellEditEvent;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.util.Callback;

/**
 * FXML Controller class
 *
 * @author REDDYS
 */
public class SalesController implements Initializable {

    Stage stage;
    private final ObservableList<PurchaseOrderDetails> data =  FXCollections.observableArrayList();
    private  ObservableList dataList =  FXCollections.observableArrayList();
    
    @FXML
    TableView tableView;
    
    @FXML
    ComboBox vendor;
    
    @FXML
    TextField saleID;
    
    @FXML
    TextField saledDate;
    
    @FXML
    TextField contactPerson;
        
    @FXML
    TextField phone;
        
    @FXML
    TextField location;
    
    @FXML
    VBox vbox1;
    
    @FXML
    TextField soldBy;
    
    @FXML
    AnchorPane datePickerAnchorPane;
    
    DatePicker birthdayDatePicker = new  DatePicker();
    /**
     * Initializes the controller class.
     */
    @Override
    public void initialize(URL url, ResourceBundle rb) {
       this.stage = Inventory.stage;
       tableView.setEditable(true);
       loadTableColumns(tableView);
       addEmptyRows();
         birthdayDatePicker = new DatePicker(Locale.ENGLISH);
         birthdayDatePicker.setDateFormat(new SimpleDateFormat("dd-MM-yyyy"));
         birthdayDatePicker.getCalendarView().todayButtonTextProperty().set("Today");
         birthdayDatePicker.getCalendarView().setShowWeeks(false);
         birthdayDatePicker.getStylesheets().add("/DatePicker.css");
         datePickerAnchorPane.getChildren().add(birthdayDatePicker);
         DatePicker.setHgrow(birthdayDatePicker, Priority.ALWAYS);
      
         dataList = getSalesService().getVendorList();
         vendor.getItems().addAll(dataList);
         vendor.focusedProperty().addListener(new ChangeListener<Boolean>() {
            @Override
            public void changed(ObservableValue observable, Boolean oldValue, Boolean newValue) {
                
                     System.out.println(vendor.getSelectionModel());
                     Vendor sevendor = (Vendor) vendor.getSelectionModel().getSelectedItem();
                     if(sevendor!=null){
                         contactPerson.setText(null);
                         phone.setText(null);
                         location.setText(null);
                      
                     contactPerson.setText(sevendor.getContactperson());
                     phone.setText(sevendor.getContactpersonnumber());
                     location.setText(sevendor.getAddress1()+" "+sevendor.getAddress2()!=null?sevendor.getAddress2():"");
                     }else{
                         contactPerson.setText(null);
                         phone.setText(null);
                         location.setText(null);
                     }
                    
                
            }
        });
      // new  AutoCompleteComboBoxListener(vendor,dataList);
      // new AutoCompleteTextboxListener(purchaseOrderID,dataList);
    }    

    private void loadTableColumns(TableView tableView) {
        tableView.setEditable(true);
       TableColumn productCategory = new TableColumn("Product Category");
        productCategory.setMinWidth(100);
        Callback<TableColumn, TableCell> cellFactory =
             new Callback<TableColumn, TableCell>() {
                 public TableCell call(TableColumn p) {
                    return new EditingCell();
                 }
             };
        productCategory.setCellFactory(new Callback<TableColumn, TableCell>() {
                 public TableCell call(TableColumn p) {
                    return new EditingCell("ProductCategory");
                 }
             });

        TableColumn productID = new TableColumn("Product ID");
        productID.setMinWidth(100);
        productID.setCellValueFactory(
                new PropertyValueFactory<PurchaseOrderDetails, String>("productId"));
       productID.setCellFactory(new Callback<TableColumn, TableCell>() {
                 public TableCell call(TableColumn p) {
                     
                    return new EditingCell("ProductID");
                 }
             });
        productID.setOnEditCommit(
            new EventHandler<CellEditEvent<PurchaseOrderDetails, String>>() {
                @Override
                public void handle(CellEditEvent<PurchaseOrderDetails, String> t) {
                    System.out.println("handle after set"+t.getTableView().getItems().get(t.getTablePosition().getRow()).getProductId());
                }
             }
        );
 
        TableColumn productName = new TableColumn("Product Name");
        productName.setMinWidth(200);
        productName.setCellValueFactory(
                new PropertyValueFactory<PurchaseOrderDetails, String>("productDescription"));
        
       // productName.setCellFactory(cellFactory);
        
        TableColumn itemCode = new TableColumn("Item Code");
        itemCode.setMinWidth(100);
        itemCode.setCellValueFactory(
                new PropertyValueFactory<PurchaseOrderDetails, String>("itemCode"));
        //itemCode.setCellFactory(cellFactory);
 
        TableColumn quantity = new TableColumn("Quantity");
        quantity.setMinWidth(200);
        quantity.setCellValueFactory(
                new PropertyValueFactory<PurchaseOrderDetails, String>("batchCode"));
        quantity.setCellFactory( new Callback<TableColumn, TableCell>() {
                 public TableCell call(TableColumn p) {
                    return new EditingCell("Quantity");
                 }
             });
        quantity.setOnEditCommit(
            new EventHandler<CellEditEvent<PurchaseOrderDetails, String>>() {
                @Override
                public void handle(CellEditEvent<PurchaseOrderDetails, String> t) {
                    System.out.println("handle event for quantity");
                    ((PurchaseOrderDetails) t.getTableView().getItems().get(
                        t.getTablePosition().getRow())
                        ).setQuantity(new Double(t.getNewValue()));
                }
             }
        );
        
        TableColumn uom = new TableColumn("Uom");
        uom.setMinWidth(200);
        uom.setCellValueFactory(
                new PropertyValueFactory<PurchaseOrderDetails, String>("standardUom"));
        uom.setCellFactory( new Callback<TableColumn, TableCell>() {
                 public TableCell call(TableColumn p) {
                    return new EditingCell("UOM");
                 }
             });
        
        TableColumn unitPrice = new TableColumn("Unit Price");
        unitPrice.setMinWidth(100);
        unitPrice.setCellValueFactory(
                new PropertyValueFactory<PurchaseOrderDetails, String>("cost"));
        unitPrice.setCellFactory( new Callback<TableColumn, TableCell>() {
                 public TableCell call(TableColumn p) {
                    return new EditingCell("UnitPrice");
                 }
             });
 
        TableColumn discount = new TableColumn("Discount");
        discount.setMinWidth(200);
        discount.setCellValueFactory(
                new PropertyValueFactory<PurchaseOrderDetails, String>("discount"));
        discount.setCellFactory( new Callback<TableColumn, TableCell>() {
                 public TableCell call(TableColumn p) {
                    return new EditingCell("Discount");
                 }
             });
        
        TableColumn subTotal = new TableColumn("Sub Total");
        subTotal.setMinWidth(200);
        subTotal.setCellValueFactory(
                new PropertyValueFactory<PurchaseOrderDetails, String>("cost"));
        subTotal.setCellFactory( new Callback<TableColumn, TableCell>() {
                 public TableCell call(TableColumn p) {
                    return new EditingCell("SubTotal");
                 }
             });
        tableView.getColumns().addAll(productCategory, productID, productName,itemCode, quantity, uom,unitPrice, discount, subTotal);
        tableView.setItems(data);
 
    }

    @FXML
    private void addEmptyRows() {
        for(int i=0;i<10;i++){
         data.add(new PurchaseOrderDetails());
        }
    }
    
    @FXML
    private void clearRows() {
        tableView.getItems().clear();
    }
    
    @FXML
    private void save() {
        try{
        if(validateSave()){
        Sale  sale = new Sale();
        System.out.println("dale"+birthdayDatePicker.getSelectedDate());
        System.out.println("customer"+contactPerson.getText());
        sale.setSaleDate(birthdayDatePicker.getSelectedDate());
        sale.setCustomerDetails(contactPerson.getText());
        sale.setSoldBy(soldBy.getText());
        sale.setDateCreated(new Date());
        sale = getSalesService().saveHeader(sale);
    for(int i =0;i<tableView.getItems().size();i++){
        SaleDetails saleDetails = new SaleDetails();
        PurchaseOrderDetails purchaseOrderDetails = (PurchaseOrderDetails) tableView.getItems().get(i);
        System.out.println("purchaseOrderDetails ----------->"+purchaseOrderDetails);
       if(sale.getSaleId()!=null && sale.getSaleId()!=""){
            saleDetails.setSaleId(sale);
        }
        if(purchaseOrderDetails.getProductId()!=null && purchaseOrderDetails.getProductId()!=""){
            Double amount = (purchaseOrderDetails.getQuantity()*purchaseOrderDetails.getUnitPrice());
            purchaseOrderDetails.setSubTotal(amount);
            saleDetails.setProductId(purchaseOrderDetails.getProductId());
            saleDetails.setProductCategory(purchaseOrderDetails.getProductCategory());
            saleDetails.setQuantity(purchaseOrderDetails.getQuantity());
            saleDetails.setUom(purchaseOrderDetails.getUom());
            saleDetails.setUnitPrice(purchaseOrderDetails.getUnitPrice());
            saleDetails.setDiscount(purchaseOrderDetails.getDiscount());
            saleDetails.setNetPrice(purchaseOrderDetails.getSubTotal());
            saleDetails.setDateCreated(new Date());
            getSalesService().save(saleDetails);
            
            Stock stock = getSalesService().getStock(saleDetails.getProductId());
            if(stock!=null){
            stock.setAvailableQuantity(stock.getAvailableQuantity()-saleDetails.getQuantity());
            getSalesService().updateStock(stock);
            }
            StockDetails stockDetails = new StockDetails();
            stockDetails.setProductId(saleDetails.getProductId());
            stockDetails.setQuantity(saleDetails.getQuantity());
            stockDetails.setStockId(stock);
            stockDetails.setTransactionId(sale.getSaleId());
            stockDetails.setTransactionType("sale");
            stockDetails.setTransactionDate(Utilities.getCurrentDate());
            getSalesService().saveStockDetails(stockDetails);
        }
    }
             Utilities.createDialog("Transaction Completed Successfully");
    }
        }catch(Exception e){
            e.printStackTrace();
            Utilities.createDialog("Transaction Failed");
        }
    
    }
    public SalesService getSalesService(){
        SalesService salesService = new SalesService();
        return salesService;
    }

    private boolean validateSave() {
        if(null == birthdayDatePicker.getSelectedDate()){
            Utilities.createDialog("Please select date");
            return false;
        }
        Vendor svendor = (Vendor) vendor.getSelectionModel().getSelectedItem();
        if(svendor==null){
            Utilities.createDialog("Please select customer");
            return false;
        }
        boolean product = false;
        boolean productId = false;
            for(int i =0;i<tableView.getItems().size();i++){
            PurchaseOrderDetails purchaseOrderDetails = (PurchaseOrderDetails) tableView.getItems().get(i);
                    System.out.println("purchaseOrderDetails ----------->"+purchaseOrderDetails);
            if(!Utilities.isNull(purchaseOrderDetails.getProductCategory())){
                if(!Utilities.isNull(purchaseOrderDetails.getProductId())){
                    productId = true;
                    if(Utilities.isNull(String.valueOf(purchaseOrderDetails.getQuantity()))){
                        Utilities.createDialog("Please enter quantity");
                        return false;
                    }
                    if(Utilities.isNull(String.valueOf(purchaseOrderDetails.getUnitPrice()))){
                        Utilities.createDialog("Please enter unit price");
                        return false;
                    }                                        
                }
                product = true;
            }
            }
        if(!product){
            Utilities.createDialog("Please enter atleast one detail");
            return false;
        }
        if(!productId){
            Utilities.createDialog("Please select product ID");
            return false;
        }
        
        return true;
    }
}
